package com.dingwen.treasure.web.response;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.base.pojo.vo.ResultGenerator;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 　ResponseAdvice: 统一响应内容封装
 * 　@author dingwen
 * 　@date 2022/8/8
 */
@RestControllerAdvice("com.dingwen.treasure")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 此处可以处理不需要进行封装返回的接口
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (Objects.isNull(body)) {
            return ResultGenerator.genSuccessResult();
        }

        if (body instanceof Result) {
            return body;
        }

        if (body instanceof Boolean) {
            return ResultGenerator.genResult(Convert.toBool(body));
        }

        if (body instanceof String) {
            return JSONUtil.toJsonStr(ResultGenerator.genSuccessResult(body));
        }

        return ResultGenerator.genSuccessResult(body);
    }
}
